package com.google.code.openperfmon.web;

import javax.servlet.http.Cookie;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.google.code.openperfmon.domain.AppUser;
import com.google.code.openperfmon.service.ServiceFactory;

public class UserSession {
	private static final String KEY = UserSession.class.getName();
	private static final String REMEMBER_ME = "REMEMBER_ME";
	
	public static AppUser authUser() {
		return (AppUser)ServletActionContext.getRequest().getSession(true).getAttribute(KEY);
	}
	
	public static AppUser cookieAuth() {
		Cookie [] cookies = ServletActionContext.getRequest().getCookies();
		if (cookies != null) for (Cookie c : cookies) {
			if (REMEMBER_ME.equals(c.getName())) {
				if (StringUtils.isBlank(c.getValue())) break;
				AppUser usr = ServiceFactory.getUserService().authenticate(c.getValue());
				if (usr != null) {
					putAuthUserToSession(usr);
					return usr;
				}
			}
		}
		
		return null;
	}
	
	public static boolean authenticate(String login, String password, boolean remember) {
		AppUser user = ServiceFactory.getUserService().authenticate(login, password);
		if (user == null) return false;
		putAuthUserToSession(user);
		Cookie c = new Cookie(REMEMBER_ME, ServiceFactory.getUserService().encode(user));
		c.setMaxAge(365 * 24 * 60 * 60); //year
		if (remember) ServletActionContext.getResponse().addCookie(c);
		return true;
	}
	
	public static void logout() {
		ServletActionContext.getRequest().getSession(true).removeAttribute(KEY);
		Cookie c = new Cookie(REMEMBER_ME, null);
		c.setMaxAge(0); 
		ServletActionContext.getResponse().addCookie(c);
	}
	
	private static void putAuthUserToSession(AppUser user) {
		ServletActionContext.getRequest().getSession(true).setAttribute(KEY, user);
	}
}
